import React, {Component} from 'react'

class StateTravel extends Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
        this.archive = [];
        this.currentIndex = 0;
        this.state = {
            current: []
        };

        //init this.archive
        this.archive.push(this.state.current);
    }

    componentDidMount() {
        this.inputRef.current.focus();
    }

    _addListItem = () => {
        let currentInputContent = this.inputRef.current.value;
        let currentCopy = this.state.current.slice();

        if (currentInputContent) {
            currentCopy.push(currentInputContent);

            this.setState({
                current: currentCopy
            }, () => {
                this.archive.push(this.state.current);
                this.currentIndex += 1;
            })
        }
    };

    _redo = () => {
        const _self = this;
        const nextIndex = this.currentIndex + 1;
        let nextState;
        if (nextIndex < this.archive.length) { //防止越界
            nextState = this.archive[nextIndex];

            this.setState({
                current: nextState
            }, () => {
                _self.currentIndex = _self.currentIndex + 1;
            })
        }
    };

    _undo = () => {
        const _self = this;
        const previousIndex = this.currentIndex - 1;
        let previousState;
        if (previousIndex > -1) { //防止越界
            previousState = this.archive[previousIndex];

            this.setState({
                current: previousState
            }, () => {
                _self.currentIndex = _self.currentIndex - 1;
            })
        }
    };

    render() {
        const list = this.state.current.map(function (item) {
            return <li key={Math.random()}>{item}</li>
        });
        return (
            <div>
                <MyInput ref={this.inputRef}/>
                <button onClick={this._addListItem}>Add</button>
                <ul style={{'listStyle': 'none'}}>{list}</ul>
                <button onClick={this._undo}>Undo</button>
                <button onClick={this._redo}>Redo</button>
            </div>
        )
    }
}

const MyInput = React.forwardRef((props, ref) => <TextInput refs={ref}/>);

class TextInput extends Component {
    render() {
        return (
            <input type="text" ref={this.props.refs}/>
        )
    }
}

export default StateTravel;